Connecting Nextjs Project with MongoDB Atlas

          The format I am telling here will be useful if you are using app router and no src directory in your project, but you should easily be able to extrapolate it for other formats as well.

          Step 1: Make a Database for your project
        • SignIn to your MongoDB Atlas
        • On left scroll bar, 
            Click on Database -> Create Database -> Enter Database name and Collection name -> click on create

        Step 2: Get your connection string
        • After creating the database, MongoDB Atlas will prompt you to connect to it.
        • Choose "Connect your application".
        • Select Driver as Node.js and version as 4.0 or later.
        • Copy the provided connection string — it will look something like this:
                mongodb+srv://<username>:<password>@cluster0.xxxxx.mongodb.net/?retryWrites=true&w=majority&appName=Cluster0
        
        
                
        Step 3: Add the connection string to environment variables
        • In your root folder, create a .env.local file.
        • Add the following line:
                
         MONGODB_URI=mongodb+srv://<username>:<password>@cluster0.xxxxx.mongodb.net/myDatabase?retryWrites=true&w=majority&appName=Cluster0
        
        
                
        Step 4: Get username and password
        • On Left scrollbar in MongoDB Atlas, click on Database Access
        • Click on "Add new database user"
        • Enter Username and Password
        • In built-in role select "Read and write to any database"
        • Click on Add User

        Step 5: Create a MongoDB utility file
        • In the root of your project (same level as app/), create a file lib/mongodb.js or utils/mongodb.js
        • Add the following code:
                
        // lib/mongodb.js

        import { MongoClient } from 'mongodb'

        const uri = process.env.MONGODB_URI
        const options = {
          useNewUrlParser: true,
        }

        let client
        let clientPromise

        if (!process.env.MONGODB_URI) {
          throw new Error('Add Mongo URI to .env.local')
        }

        if (process.env.NODE_ENV === 'development') {
          if (!global._mongoClientPromise) {
            client = new MongoClient(uri, options)
            global._mongoClientPromise = client.connect()
          }
          clientPromise = global._mongoClientPromise
        } else {
          client = new MongoClient(uri, options)
          clientPromise = client.connect()
        }

        export default clientPromise

        Step 6: Use MongoDB inside API routes

        • Let’s say you’re using the App Router. Inside app/api/add/route.js, you can now do:
                
        import clientPromise from "@/lib/mongodb";
        import { NextResponse } from "next/server";

        export async function POST(request) {
          const body = await request.json();
          const client = await clientPromise;
          const db = client.db("Blogs");
          const collection = db.collection("Blog");

          const doc = await collection.findOne({ title: body.title });

          if (doc) {
            return NextResponse.json({
              success: false,
              error: true,
              message: 'This Title already exists',
              result: null
            });
          }

          const result = await collection.insertOne(body);

          return NextResponse.json({
            success: true,
            error: false,
            message: 'Your Blog has been Published',
            result: result
          });
        }

        export async function GET(request) {
          const client = await clientPromise;
          const db = client.db("Blogs");
          const collection = db.collection("Blog");

          const blogs = await collection.find().toArray();

          // console.log(blogs);
         
          return NextResponse.json(blogs);
        }
        • The POST function will be accessed for POST req and GET function will be accessed for GET req.
        • You can also define other requests in the same route file.

        Example of sending a POST request:
                
          const handleSave = async (title) => {
            const content = document.getElementById("editor").innerHTML;

            await fetch("/api/add", {
              method: "POST",
              headers: { "Content-Type": "application/json" },
              body: JSON.stringify({ title: title, html: content }),
            });
            toast("Successfully Published")
            redirect("/all")
          };



        Thanks for reading.....
        - Pratyush Khengle